const globalData = JSON.parse(JSON.stringify(getApp().globalData));

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

const toast = (text, icon, d)=>{
  wx.showToast({
    title:text,
    icon:icon==undefined?'none':icon,
    duration:d==undefined?1500:d
  })
}
const apiRequest = (path, type, data)=>{
  return new Promise((result)=>{
    wx.request({
      url: globalData.server_ip + path,
      method: type?type:'GET',
      data: data?typeof(data)=='object'?JSON.stringify(data):data:'',
      success: (res)=>{
        if(res.errMsg=='request:ok'){
          return result({code: 1, data: res.data});
        }
        return result({code: 0, errMsg: res.errMsg});
      },
      fail: (err)=>{
        result({code: 0, errMsg:err.errMsg});
      }
    })
  });
} 

module.exports = {
  toast,
  formatTime,
  apiRequest
}
